<template>
  <eui-background type="common">
    <view class="content-img">
      <eui-nav-bar ref="BcmNavBar" title="重量退差" />
      <view class="footer" :style="{ height: height + 'px' }" v-if="goodsList.length > 0">
        <view
          style="width: 100%; background: #FFE9DA;padding: 15rpx 20rpx 15rpx 15rpx;color:#FF0000;box-sizing: border-box;font-size: 32rpx;line-height: 35rpx;"
          class="flex just-between align-center">
          <view style="flex: 1;">提示：为避免顾客投诉，建议在操作退款前与顾客联系协商一致</view>
          <view
            style="padding:6rpx 10rpx;height: 35rpx;border-radius: 3rpx;border: 1rpx solid #FF0000;text-align: center;line-height: 35rpx;margin-left: 22rpx;"
            @click="openContactCustPop" v-if="!!consigneePhone">
            联系顾客</view>
        </view>
        <view style="height: 65rpx;font-size: 32rpx;line-height: 65rpx;padding: 0 17rpx 0 10rpx;box-sizing: border-box;"
          class="flex align-center just-between">
          <view>请选择需要退差的商品</view>
        </view>
        <scroll-view scroll-y="true" class="bg-white"
          style="width: 100%;padding: 10rpx 18rpx;box-sizing: border-box;overflow-y: scroll;">
          <view>
            <view class="goods-item" v-for="(item, index) in goodsList" :key="index">
              <checkbox-group @change="checkboxChange(index)">
                <checkbox :value="item.orderGoodsId" :checked="item.checked" />
              </checkbox-group>
              <view
                style="width: 40rpx;height: 40rpx;text-align: center;line-height: 40rpx;background-color: #D8D8D8;color: #fff;border-radius: 40rpx;font-size: 32rpx;margin-top: 13rpx;">
                {{ index + 1 }}
              </view>
              <view style="margin-left: 17rpx;box-sizing: border-box;flex: 1;">
                <view class="goods-info just-between">
                  <view style="">
                    <view class="goods-name bold">{{ item.goodsName }}</view>
                    <view style="font-size: 32rpx;color: #626262;">
                      {{ item.goodsCode }}-{{ item.goodsBarcode }}
                    </view>
                  </view>
                  <view style="color: #626262;text-align: right;">
                    <view style="font-weight: bold;" class="goods-quantity">¥ {{ item.goodPrice
                      }}</view>
                    <view class="goods-quantity">
                      可退数量<text style="font-weight: bold;color: #000;margin-left: 4rpx;">{{
        item.partRefundGoodsNum }}</text></view>
                  </view>
                </view>
                <view v-show="item.checked">
                  <view
                    style="background: #FFEFD4;border-radius: 3rpx;padding: 8rpx;font-size: 23rpx;line-height: 30rpx;margin: 12rpx 0;color: #717171;"
                    v-if="item.partRefundGoodsNum > 1">提示：每件商品可单独填写退货克重，请至少填写1件商品的克重</view>
                  <view v-for="(f, i) in item.refundGoodsActualWeights" :key="i">
                    <view
                      style="display: flex;justify-content: space-between;margin-top: 6rpx;height: 48rpx;font-size: 32rpx;color: #000;">
                      <view class="flex align-center co-00">
                        <view
                          style="width: 72rpx; height: 28rpx; background: #D4F2FF; border-radius: 3rpx;text-align: center;line-height: 28rpx;color: #4B9BFF;font-size: 28rpx;padding:4rpx 0;margin-right: 6rpx;">
                          退差</view>
                        <view class="goods-price">
                          应拣 <text style="font-weight: bold;margin-left: 6rpx;" class="co-00">{{ f.preValue }}g</text>
                        </view>
                      </view>
                      <view style="font-size: 32rpx;" class="flex align-center">
                        <view class="co-00">实拣</view>
                        <view
                          style="width: 203rpx;height: 52rpx;margin-left:6rpx;background-color: #F1F1F1;padding: 6rpx;box-sizing: border-box;"
                          class="flex">
                          <input placeholder="请输入"
                            placeholder-style="color:#959595;font-size: 32rpx;font-weight:initial;" type="number"
                            @blur="handleInputWeight" :data-index="index" :data-i="i"
                            style="padding: 2rpx 0 2rpx 2rpx;font-weight: bold;" />
                          <text class="bold">g</text>
                          <!-- :value="item?.applyRefundWeight[i]?.value" -->
                        </view>
                      </view>
                    </view>
                    <view style="font-size: 32rpx;text-align: right;color: #E43E00;height: 48rpx;margin-top: 16rpx;">
                      预计退差 <text> {{ formatPriceText(item.applyRefundPrice[i]) }}</text><text
                        style="color: #000000;">/¥{{ item.goodPrice }}</text>
                    </view>
                  </view>
                </view>
              </view>
            </view>
            <view style="padding: 20rpx 0;">
              <view style="font-size: 32rpx;" class="flex just-between bold">
                <view class="bold">退差件数</view>
                <view>{{ sumNum() }}</view>
              </view>
              <view style="font-size: 32rpx;margin-top: 6rpx" class="flex just-between bold">
                <view class="">合计退款</view>
                <view style="color: #E43E00;">¥{{ sum() }}</view>
              </view>
            </view>
          </view>
        </scroll-view>
      </view>
      <view class="footer align-center" :style="{ height: height + 'px' }" v-else>
        <view class="m-list-template-image" style="flex: 1;margin-top: 25%;">
          <image src="@/static/img/status/blank_order.png" />
          <view style="color: #9e9e9e;font-size: 14px;text-align: center;">无可退商品</view>
        </view>
      </view>
      <eui-button title="下一步" type="max" singleTag="confirm" @buttonClick="buttonClick"
        style="width: 100%;height: 86rpx;line-height: 86rpx;margin: 0!important;border-radius: 0;padding: 0;"
        :disabled="sumNum() == 0 || sum() == 0"></eui-button>
    </view>
    <eui-popup ref="popup" background-color="#fff" type="bottom" :mask-click="false">
      <view class="popup-content">
        <view class="popup-title flex just-between">
          <view style="font-weight: bold;">
            选择退款理由
          </view>
          <bcm-close-btn @click="close"></bcm-close-btn>
        </view>
        <scroll-view scroll-y="true"
          style="padding: 8rpx 8rpx 50rpx 30rpx;box-sizing: border-box;height: 70vh;text-align: left;">
          <view>
            <radio-group @change="selectItem">
              <view v-for="item in getBcmDictList('orderCancelReasonType')" :key="item.value">
                <radio :value="item.value" :checked="orderCancelReasonType === item.value"
                  style="margin-top: 20rpx;line-height: 35rpx">
                  {{ item.text }}
                </radio>
              </view>
            </radio-group>
            <textarea v-model="rejectReason" placeholder="请输入原因" v-if="orderCancelReasonType == '999'"
              style="border: 1px solid #ccc; width: 95%; border-radius: 10rpx; margin-top: 20rpx; padding: 20rpx; box-sizing: border-box"></textarea>
          </view>
        </scroll-view>
        <view class="bottom-1">
          <eui-button singleTag="sure" title="提交" style="width: 50%;" type="max" @buttonClick="buttonClick" />
        </view>
      </view>
    </eui-popup>
    <eui-popup ref="contactCustPopup" type="bottom" :animation="false" background-color="#fff" :mask-click="true">
      <view class="popup-content">
        <view class="popup-title flex just-between">
          <view style="font-weight: bold;">
            联系顾客
          </view>
          <bcm-close-btn @click="closeContactCustPopup"></bcm-close-btn>
        </view>
        <view
          style="padding-left: 30rpx;color: #000;background-color:#fff;box-sizing: border-box;padding-top:24rpx;text-align: left">
          <view>
            <text v-if="!!consigneeName">姓名：{{ consigneeName }}</text><text v-if="!!consigneePhoneLast">(尾号{{
        consigneePhoneLast }})</text>
          </view>
          <view>
            <text v-if="!!consigneePhone">电话：{{ consigneePhone }}</text>
          </view>
          <view class="bottom-1" style="margin: 100rpx 0 50rpx 0;">
            <eui-button type="max" title="拨打电话" style="width: 50%" singleTag="submit" @buttonClick="buttonClick" />
          </view>
        </view>
      </view>
    </eui-popup>
  </eui-background>
</template>
<script setup>
import { mapState, mapMutations } from 'vuex';
import { ref, computed, onMounted } from 'vue';
import { onLoad } from "@dcloudio/uni-app";
import service from '../../../common/service';
import { bcmRequest, getBcmUrl } from '../../../hooks/bcmServices';
import { getBcmDictList, getBcmDictName, makePhoneCall } from '../../../hooks/bcmUseUntils';
import _img_blank_order from '../../../static/img/status/blank_order.png';
import BcmCloseBtn from '../components/BcmCloseBtn.vue';

const bcmUrl = getBcmUrl()
const goodsList = ref([])
const refundType = ref('1')
const orderCancelReasonType = ref('')
const rejectReason = ref('')
const orderId = ref('')
const consigneeName = ref('')
const consigneePhone = ref('')
const consigneePhoneLast = ref('')
const orderStatus = ref('')
const chnlType = ref('')
const height = ref(0)
const popup = ref(null)
const contactCustPopup = ref(null)
const showConfigModal = ref(false)

const selectItem = function (e) {
  orderCancelReasonType.value = e.detail.value;
}

const checkboxChange = function (index) {
  let list = [...goodsList.value], item = list[index];
  item.checked = !item.checked
  goodsList.value = list;
}

const validatePositiveInteger = function (num) {
  if (!Number.isInteger(num * 1)) {
    return false;
  }
  // 判断是否大于等于0
  if (num >= 0) {
    return true;
  } else {
    return false;
  }
}

const handleInputWeight = function (e) {
  const { value } = e.detail, { dataset } = e.target;
  let list = [...goodsList.value], item = list[dataset.index], i = dataset.i, weight = item.refundGoodsActualWeights[i].preValue;
  item.applyRefundWeight[i].value = value;
  if ((!Number.isInteger(Number(value))) || Number(value) < 0 || value == '') {
    goodsList.value = list;
    uni.showToast({
      title: '请输入大于0的整数',
      icon: 'none'
    });
    setTimeout(() => {
      let remarkData = { ...item }
      remarkData.applyRefundWeight[i].value = null;
      goodsList.value[dataset.index] = remarkData
    }, 100)
    return
  }
  if (item.applyRefundWeight[i].value - weight > 0) {
    uni.showToast({
      title: '输入值不能超过' + weight,
      icon: 'none'
    });
    item.applyRefundWeight[i].value = weight;
  }

  if (item.applyRefundWeight[i].value || item.applyRefundWeight[i].value == 0) {
    let pricePerg = (item.totalPrice / item.partRefundGoodsNum) / weight;
    item.applyRefundPrice[i] = ((weight - item.applyRefundWeight[i].value) * pricePerg).toFixed(2);
  } else {
    item.applyRefundPrice[i] = null;
  }
  goodsList.value = list;
}
const sumNum = function () {
  let total = 0, list = goodsList.value.filter(a => !!a.checked);
  // 遍历数组中的每个对象
  list.map(item => {
    item.applyRefundWeight.map((a, i) => {
      if ((!!a.value || a.value == 0) && item.refundGoodsActualWeights[i].preValue != a.value) {
        total += 1;
      }
    })
  });

  return total;
}

const formatPriceText = function (number) {
  return number > 0 ? `-￥${(Number(number)).toFixed(2)}` : '-￥0.00';
}

const sum = function () {
  let total = 0, list = goodsList.value.filter(a => !!a.checked);
  // 遍历数组中的每个对象
  list.map(item => {
    item.applyRefundPrice.map(num => {
      let num1 = Number(num);
      if (!isNaN(num)) {
        total += num1;
      }
    });
  });

  return total.toFixed(2);
}

const buttonClick = async function (t, v) {
  const { singleTag } = t
  let list = goodsList.value.filter(a => !!a.checked);
  switch (singleTag) {
    case 'sure':
      if (!orderCancelReasonType.value) {
        uni.showToast({
          title: '请选择退款理由',
          icon: 'none'
        });
        return;
      }
      if (orderCancelReasonType.value == '999' && !rejectReason.value) {
        uni.showToast({
          title: '请输入退款原因',
          icon: 'none'
        });
        return;
      }
      service.enjoyShowLoading('正在处理...');
      let params = {
        orderId: orderId.value,
        reasonType: orderCancelReasonType.value,
        reasonDesc: orderCancelReasonType.value != '999' ? getBcmDictName('orderCancelReasonType', orderCancelReasonType.value) : rejectReason.value,
        refundGoodsDetailList: list.map(v => {
          return {
            orderGoodsId: v.orderGoodsId,
            refundGoodsActualWeights: v.applyRefundWeight?.sort((a, b) => a.rowNo - b.rowNo)?.map((a, i) => {
              if (!!a.value || a.value == 0) {
                return a
              } else {
                a.value = v.refundGoodsActualWeights[i].preValue;
                return a
              }
            }),
            prePartReturnInfo: v.prePartReturnInfo
          }
        })
      }
      let response = await bcmRequest(bcmUrl.orderApi, '订单表', 'orderWeightRefundDiff', params);
      service.enjoyHideLoading();
      popup.value.close('bottom');
      uni.showToast({
        title: '退款成功',
        icon: 'none'
      });
      if (response?.afsOrderId && (!['2', '1'].includes(response?.syncErpBreakageStatus)) && orderStatus.value == '4' && showConfigModal) {
        uni.navigateTo({
          url: `/pages/BcmViews/PickingOrder/breakage?afsOrderId=` + response?.afsOrderId + '&type=1'
        });
      } else {
        setTimeout(() => {
          uni.navigateBack({
            delta: 1
          });
          uni.$emit('REFRESH_ORDER_DETAIL_DATA');
          uni.$emit('REFRESH_ORDER_SEARCH_DATA')
        }, 1000)
      }
      break;
    case 'confirm':
      if (list.length == 0) {
        uni.showToast({
          title: '请选择需要退差的商品',
          icon: 'none'
        });
        return;
      }
      let total = sum();
      if (total == 0) {
        uni.showToast({
          title: '请输入退差金额',
          icon: 'none'
        });
        return;
      }
      if (list.filter(a => (a.applyRefundWeight.length > 0 && a.applyRefundWeight.filter(b => !b.value && b.value != 0).length == a.applyRefundWeight.length)).length > 0
      ) {
        uni.showToast({
          title: '请填写完整退差信息',
          icon: 'none'
        });
        return;
      }
      if (list.filter(a => a.applyRefundWeight.filter(b => b.value == 0).length == a.applyRefundWeight.length).length == list.length) {
        uni.showToast({
          title: '订单商品实拣重量不可全部为0',
          icon: 'none'
        });
        return;
      }
      popup.value.open('bottom');
      break;
    case 'submit':
      // plus.device.dial(consigneePhone.value, true);
      makePhoneCall(consigneePhone.value)
      break;
  }
}
const close = function () {
  popup.value.close();
  orderCancelReasonType.value = '';
  rejectReason.value = '';
}

const openContactCustPop = function () {
  contactCustPopup.value.open('bottom');
}

const closeContactCustPopup = function () {
  contactCustPopup.value.close();
}

onLoad((option) => {
  let options = service.getStorageSync('partOptions');
  goodsList.value = options.goodsList;
  orderId.value = options.orderId;
  consigneeName.value = options.consigneeName;
  consigneePhone.value = options.consigneePhone;
  consigneePhoneLast.value = options.consigneePhoneLast;
  chnlType.value = options.chnlType;
  orderStatus.value = option.orderStatus;
  showConfigModal.value = option.showModal || false;
})

</script>
<style lang="scss" scoped>
@import "@/static/font/enjoyicon/iconfont.css";
@import "../common/common.css";

uni-checkbox {
  ::v-deep .uni-checkbox-input {
    transform: scale(.6);
  }
}

.content {
  // background-color: $uni-background;
  padding: 0;
}

.navigation {
  flex: 0 0 auto;
}

.content-img {
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100%;
  background-repeat: no-repeat;
  // background: $uni-background-img;
  background-size: 100% 150px;
}

.footer {
  display: flex;
  flex-direction: column;
  flex: 1;
  background: #f5f7fa;
}

.bottom {
  height: 76rpx;
  padding: 0 !important;
  // text-align: center;
  background: $uni-bg-color;
}

.bottom-1 {
  display: flex;
  justify-content: center;
  flex: 0 0 auto;
  height: 70rpx;
  padding: $uni-spacing-col-sm * 2 $uni-spacing-row-sm;
  background: $uni-bg-color;
}

//list
.goods-item {
  display: flex;
  justify-content: space-between;
  padding: 24rpx;
  border-bottom: 1rpx solid #e1e1e1;
}

.goods-image {
  width: 80rpx;
  height: 80rpx;
  margin-right: 10rpx;
  border: 1px solid #eee;
  border-radius: 4rpx;
}

.goods-info {
  display: flex;
  align-items: center;
  flex: 1;
}

.goods-name {
  margin-bottom: 2px;
  font-size: 32rpx;
  line-height: 35rpx;
}

.goods-price {
  font-size: 32rpx;
  text-align: right;
}

.goods-quantity {
  color: #626262;
  font-size: 32rpx;
}

.popup-content {
  display: flex;
  flex-direction: column;
  width: 100%;
  padding: 0;
  background-color: #fff;

  .popup-title {
    display: flex;
    align-items: center;
    box-sizing: border-box;
    width: 100%;
    height: 100rpx;
    padding-right: 36rpx;
    padding-left: 30rpx;
    font-size: 33rpx;
    line-height: 100rpx;
    border-bottom: 1px solid #f1f1f1;
  }

  textarea {
    box-sizing: border-box;
    width: 100%;
    height: 80px;
    padding: 5px;
    margin: 5px 0;
    border: 1px solid #ccc;
    border-radius: 5px;
  }
}
</style>
